package hn.cch.advanced.concurrent.locks;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {

    public static void main(String[] args) {

        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();

        new Thread(() -> {
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + ":lock");

            try {
                System.out.println(Thread.currentThread().getName() + ":await begin");
                condition.await();
                System.out.println(Thread.currentThread().getName() + ":await end");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
                System.out.println(Thread.currentThread().getName() + ":unlock");

            }

            System.out.println(Thread.currentThread().getName() + ":stop");
        }, "thread-0").start();


        try {
            Thread.sleep(1);
            System.out.println(Thread.currentThread().getName() + ":sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + ":lock");

            try {
                System.out.println(Thread.currentThread().getName() + ":signal begin");

                condition.signal();
                System.out.println(Thread.currentThread().getName() + ":signal end");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
                System.out.println(Thread.currentThread().getName() + ":unlock");
            }

            System.out.println(Thread.currentThread().getName() + ":stop");

        }, "thread-1").start();
    }


}
